﻿define([
    'dojo/_base/declare',
    'esri/geometry/Point',
    'geomap/plugins/layers/DivsLayer',
    'geomap/plugins/Div',
], function (declare, Point, BaseDivsLayer, Div) {
    var DivsLayer = declare([BaseDivsLayer], {
        setData: function (mapView, layer) {
            var me = this;
            var mapUtils = mapView.mapUtils;
            var options = layer.layer || {};
            me.symbolOptions = options.options;
            var data = $.extend(true, [], options.data);
            if (options.layerIndex > -1) {
                $(me._element).css('z-index', options.layerIndex);
            }
            if (!data || data.length < 1) {
                if (typeof options.callback == 'function') {
                    options.callback(layer);
                }
                return;
            }
            me.options = options;
            var lngLatArray = mapUtils.toLngLatArray(mapView, data, options);
            var symbolFieldName = options.symbolFieldName || mapView.getSymbolFieldName();

            me.convertSr(mapView, lngLatArray, callback);

            function callback(lngLatArray, sr) {
                lngLatArray.map(function (lngLat, index) {
                    var point = mapUtils.createPoint(mapView, lngLat, { sr: sr });
                    var symbol = lngLat[symbolFieldName] || options.symbol || {};
                    var div = new Div(point);
                    div._layer = me;
                    $(div.getElement())
                        .addClass(symbol.class)
                        .css(symbol.css || {})
                        .html(symbol.html);
                    div.attributes = lngLat;
                    me.add(div);

                    if (index == lngLatArray.length - 1) {
                        if (typeof options.callback == 'function') {
                            options.callback(layer);
                        }
                    }
                });
            }
        },
        getGraphicLocation: function (mapView, esriEvent) {
            var geometry = esriEvent.graphic.geometry;
            var lngFieldName = mapView.getLngFieldName();
            var latFieldName = mapView.getLatFieldName();
            var location = {};
            location[lngFieldName] = geometry.x;
            location[latFieldName] = geometry.y;
            location.sr = this.mapSr;
            return location;
        },
    });
    return DivsLayer;
});
